<?php

namespace app\admin\controller;

use think\Cache;
use think\Controller;
use think\Db;
use think\Loader;
use think\Request;
use think\Queue;

header('Content-Type: text/html; charset=utf-8');

class Manage extends Common
{
    /**
     * 列表示例
     * */
    public function listDemo()
    {
        $list = Db::name('menu')->paginate(2);
        $this->assign('list', $list);

        $this->assign('title', '列表示例');
        return $this->fetch();
    }

    /**
     * 列表导出示例
     * */
    public function exportListDemo()
    {
        $title = '文件名';
        $th = ['标题一', '标题二', '标题三'];
        $td = ['key1', 'key2', 'key3'];
        $data = [
            [
                'key1' => 'value1',
                'key2' => 'value2',
                'key3' => 'value3',
            ], [
                'key1' => 'value1',
                'key2' => 'value2',
                'key3' => 'value3',
            ]
        ];

        exportExcel($title, $th, $td, $data);
    }

    /**
     * 表单示例
     * */
    public function formDemo()
    {
        if (Request()->isPost()) {
            $input = Request()->param();

            echo "<pre>";
            print_r($input);
            exit;
        }
        $this->assign('title', '表单示例');
        return $this->fetch();
    }

    /**
     * 视频分片上传示例
     * */
    public function uploadVideo()
    {
        $this->assign('title', '视频分片上传示例');
        return $this->fetch();
    }

    /**
     * 统计图示例
     * */
    public function chartDemo()
    {
        $this->assign('title', '统计图');
        return $this->fetch();
    }

    /**
     * 树形列表示例
     * */
    public function treeDemo()
    {
        return $this->fetch();
    }

    public function test()
    {
        return $this->view->fetch();
    }

    /**
     * 树状图原始demo
     * */
    public function tree()
    {
        $this->assign('title', 'test');
        return $this->fetch();
    }

    /**
     * iconfont
     * */
    public function iconfont()
    {
        $this->assign('title', 'iconfont');
        return $this->fetch();
    }

    /**
     * 门店账号列表
     * */
    public function shopAccountList()
    {
        $login_id = session('id');

        $where['is_admin'] = 1;
        if ($login_id == 1) {
            $where['shop_id'] = ['neq', 0];
        } else {
            $shop_id = session('shop_id');
            $where['shop_id'] = $shop_id;
        }

        $list = Db::name('user')->where($where)->paginate();
        $this->assign('list', $list);

        $this->assign('title', '门店账号列表');
        return $this->fetch();
    }

    /**
     * 新增/编辑 门店账号
     * */
    public function doShopAccount()
    {
        if (Request()->isPost()) {
            $input = Request()->param();

            $id = $input['id'];
            $account = $input['account'];
            $shop_id = $input['shop_id'];
            $password = $input['password'];
            $re_password = $input['re_password'];

            if (empty($account)) adminReturn(2, '请输入账号');
            if (strlen($account) < 6) adminReturn(2, '账号长度至少6位');
            if (empty($shop_id)) adminReturn(2, '请选择门店');
            if (empty($id)) {
                if (empty($password)) adminReturn(2, '请输入密码');
                if (empty($re_password)) adminReturn(2, '请输入确认密码');
                if (strlen($password) < 6) apiReturn(2, '密码长度至少6位');
            }
            if ($password !== $re_password) adminReturn(2, '两次密码不一致，请重新输入');

            if ($id) $where['id'] = ['neq', $id];
            $where['account'] = $account;
            $where['is_admin'] = 1;

            $count = Db::name('user')->where($where)->count();
            if ($count) adminReturn(2, '账号已存在');

            if ($id) {
                $data = [
                    'account' => $account,
                    'username' => $account,
                    'shop_id' => $shop_id,
                    'update_time' => time()
                ];

                if ($password) $data['password'] = thinkEncrypt($password);

                $res = Db::name('user')->where(['id' => $id])->update($data);
                $msg = '编辑';
            } else {
                $data = [
                    'account' => $account,
                    'shop_id' => $shop_id,
                    'username' => $account,
                    'status' => 1,
                    'is_admin' => 1,
                    'create_time' => time()
                ];
                if ($password) $data['password'] = thinkEncrypt($password);

                $res = Db::name('user')->insert($data);

                $msg = '新增';
            }

            if ($res) {
                adminReturn(1, $msg . '成功', url('shopAccountList'));
            } else {
                adminReturn(2, $msg . '失败');
            }


        } else {
            $id = Request()->param('id');

            if ($id) $info = Db::name('user')->where(['id' => $id])->find();
            $this->assign('info', $info);

            $where['is_del'] = 0;

            $shop_id = session('shop_id');
            if ($shop_id) $where['id'] = $shop_id;

            $shop_list = Db::name('shop')->where($where)->select();
            $this->assign('shop_list', $shop_list);


            $this->assign('title', ($id ? '编辑' : '新增') . '门店账号');
            return $this->view->fetch();
        }
    }


    /**
     * 客户列表
     * */
    public function customerList()
    {
        $shop_id = session('shop_id');

        $where['is_admin'] = 0;
        if ($shop_id) $where['c.shop_id'] = $shop_id;

        $list = Db::name('user u')->join('cater_customer c', 'u.id = c.user_id')
            ->field('c.id,u.username,u.avatar,c.success_order_count,c.fail_order_count,c.integral,c.is_staff')
            ->where($where)
            ->paginate();

        $this->assign('list', $list);
        $this->assign('title', '客户列表');
        return $this->view->fetch();
    }

    public function setStaff()
    {
        $input = Request()->param();

        $id = $input['id'];

        if (empty($id)) adminReturn(2, 'ID缺失');

        $res = Db::name('customer')->where(['id' => $id])->setField('is_staff', 1);
        if ($res) {
            adminReturn(1, '操作成功');
        } else {
            adminReturn(2, '操作失败');
        }
    }
    public function cancelStaff()
    {
        $input = Request()->param();

        $id = $input['id'];

        if (empty($id)) adminReturn(2, 'ID缺失');

        $res = Db::name('customer')->where(['id' => $id])->setField('is_staff', 0);
        if ($res) {
            adminReturn(1, '操作成功');
        } else {
            adminReturn(2, '操作失败');
        }
    }

    /**
     * 编辑
     * */
    public function doUser()
    {
        if (Request()->isPost()) {
            $input = Request()->param();

            $id = $input['id'];
            $username = $input['username'];
            $mobile = $input['mobile'];
            $avatar = $input['avatar'];
            //            $up_user_id = $input['up_user_id'];

            if (empty($username)) adminReturn(2, '请输入姓名');
            if (empty($mobile)) adminReturn(2, '请输入电话');

            $count = Db::name('user')->where(['mobile' => $mobile, 'id' => ['neq', $id]])->count();
            if ($count) adminReturn(2, '该电话已存在');

            $time = time();
            $data = [
                'username' => $username,
                'mobile' => $mobile,
                'avatar' => $avatar
                //                'up_user_id' => $up_user_id
            ];

            if ($id > 0) {
                //编辑
                $data['update_time'] = $time;

                $res = Db::name('user')->where(['id' => $id])->update($data);
                if ($res) {
                    adminReturn(1, '编辑成功', url('userList'));
                } else {
                    adminReturn(2, '编辑失败');
                }
            } else {
                //新增
                $data['create_time'] = $time;

                $res = Db::name('user')->insert($data);
                if ($res) {
                    adminReturn(1, '新增成功', url('userList'));
                } else {
                    adminReturn(2, '新增失败');
                }
            }
        } else {
            $id = Request()->param('id');
            $info = Db::name('user')->where(['id' => $id])->find();

            $user_list = Db::name('user')->where(['is_admin' => 0, 'status' => 1, 'id' => ['neq', $id]])->select();
            $this->assign('user_list', $user_list);

            $this->assign('title', ($id > 0 ? '编辑' : '新增') . '用户');
            $this->assign('info', $info);

            return $this->view->fetch();
        }
    }

    /**
     * 等级变更
     * */
    public function changeUserLevel()
    {
        $input = Request()->param();

        $id = $input['id'];
        $level = $input['level'];
        $reason = $input['reason'];

        if (empty($id)) adminReturn(2, '用户ID缺失');
        if (empty($level)) adminReturn(2, '请选择变更级别');
        if (empty($reason)) adminReturn(2, '请输入变更原因');

        Db::startTrans();
        try {
            $time = time();

            $old_level = Db::name('user')->where(['id' => $id])->value('level');
            $do_user_id = session('id');
            $data = [
                'do_user_id' => $do_user_id,
                'user_id' => $id,
                'old_level' => $old_level,
                'level' => $level,
                'reason' => $reason,
                'create_time' => $time
            ];
            Db::name('level_change')->insert($data);

            $user_data = [
                'level' => $level,
                'update_time' => $time
            ];
            Db::name('user')->where(['id' => $id])->update($user_data);

            Db::commit();
            adminReturn(1, '变更级别成功');
        } catch (\Exception $e) {
            Db::rollback();
            adminReturn(2, '系统繁忙，请稍后再试');
        }
    }

    /**
     * 级别变更记录
     * */
    public function levelChangeList()
    {
        $input = Request()->param();

        $username = $input['username'];
        $mobile = $input['mobile'];
        $start_time = $input['start_time'];
        $end_time = $input['end_time'];

        if (!empty($username)) $where["u.username"] = ["like", "%" . $username . "%"];
        if (!empty($mobile)) $where["u.mobile"] = ["like", "%" . $mobile . "%"];

        if (!empty($start_time) && empty($end_time)) {
            $where["l.create_time"] = ["egt", strtotime($start_time)];
        } elseif (empty($start_time) && !empty($end_time)) {
            $where["l.create_time"] = ["elt", strtotime($end_time) + 60 * 60 * 24 - 1];
        } elseif (!empty($start_time) && !empty($end_time)) {
            $where["l.create_time"] = ['between', [strtotime($start_time), strtotime($end_time) + 60 * 60 * 24 - 1]];
        }

        $list = Db::name('level_change l')->join('cater_user u', 'l.user_id = u.id', 'left')
            ->field('l.user_id,l.do_user_id,u.username,u.mobile,l.level,l.old_level,l.reason,l.create_time')
            ->where($where)
            ->order('l.create_time desc')
            ->paginate()->each(function ($val) {
                $username = Db::name('user')->where(['id' => $val['user_id']])->value('username');
                $val['username'] = $username;
                $do_username = Db::name('user')->where(['id' => $val['do_user_id']])->value('username');
                $val['do_username'] = $do_username;

                return $val;
            });
        $this->assign('list', $list);

        $this->assign('title', '级别变更记录');
        return $this->view->fetch();
    }

    /**
     * 余额变更
     * */
    public function balanceChange()
    {
        $input = Request()->param();

        $id = $input['id'];
        $type = $input['type'];
        $price = $input['price'];
        $reason = $input['reason'];

        if (empty($id)) adminReturn(2, '用户ID缺失');
        if (empty($type)) adminReturn(2, '请选择变更类型');
        if (empty($price) || $price <= 0) adminReturn(2, '请输入正确的变更金额');
        if (empty($reason)) adminReturn(2, '请输入变更原因');

        Db::startTrans();
        try {
            $time = time();
            $old_balance = Db::name('user')->where(['id' => $id])->value('balance');
            $do_user_id = session('id');
            // 新增余额变更记录
            $data = [
                'do_user_id' => $do_user_id,
                'user_id' => $id,
                'type' => $type,
                'old_balance' => $old_balance,
                'price' => $price,
                'reason' => $reason,
                'create_time' => $time
            ];
            Db::name('balance_change')->insert($data);

            $balance_type = $type == 1 ? 4 : 5;

            // 新增余额记录
            $balance_data = [
                'user_id' => $id,
                'balance' => $type == 1 ? $price : 0 - $price,
                'type' => $balance_type,
                'create_time' => $time
            ];
            Db::name('balance_log')->insert($balance_data);

            // 变更用户余额
            if ($type == 1)
                Db::name('user')->where(['id' => $id])->setInc('balance', $price);
            else
                Db::name('user')->where(['id' => $id])->setDec('balance', $price);

            Db::commit();
            adminReturn(1, '变更余额成功');
        } catch (\Exception $e) {
            Db::rollback();
            adminReturn(2, '系统繁忙，请稍后再试' . $e);
        }
    }

    /**
     * 余额变更记录
     * */
    public function balanceChangeList()
    {
        $input = Request()->param();

        $username = $input['username'];
        $mobile = $input['mobile'];
        $type = $input['type'];
        $start_time = $input['start_time'];
        $end_time = $input['end_time'];

        if (!empty($username)) $where["u.username"] = ["like", "%" . $username . "%"];
        if (!empty($mobile)) $where["u.mobile"] = ["like", "%" . $mobile . "%"];
        if (!empty($type)) $where['p.type'] = $type;

        if (!empty($start_time) && empty($end_time)) {
            $where["p.create_time"] = ["egt", strtotime($start_time)];
        } elseif (empty($start_time) && !empty($end_time)) {
            $where["p.create_time"] = ["elt", strtotime($end_time) + 60 * 60 * 24 - 1];
        } elseif (!empty($start_time) && !empty($end_time)) {
            $where["p.create_time"] = ['between', [strtotime($start_time), strtotime($end_time) + 60 * 60 * 24 - 1]];
        }

        $list = Db::name('balance_change p')->join('cater_user u', 'p.user_id = u.id', 'left')
            ->field('p.user_id,p.do_user_id,u.username,u.mobile,p.type,p.old_balance,p.price,p.reason,p.create_time')
            ->where($where)
            ->order('p.create_time desc')
            ->paginate()->each(function ($val) {
                $username = Db::name('user')->where(['id' => $val['user_id']])->value('username');
                $val['username'] = $username;
                $do_username = Db::name('user')->where(['id' => $val['do_user_id']])->value('username');
                $val['do_username'] = $do_username;

                return $val;
            });
        $this->assign('list', $list);

        $this->assign('title', '余额变更记录');
        return $this->view->fetch();
    }

    /**
     * 积分变更
     * */
    public function integralChange()
    {
        $input = Request()->param();

        $id = $input['id'];
        $type = $input['type'];
        $integral = $input['integral'];
        $reason = $input['reason'];

        if (empty($id)) adminReturn(2, '用户ID缺失');
        if (empty($type)) adminReturn(2, '请选择变更类型');
        if (empty($integral) || $integral <= 0) adminReturn(2, '请输入正确的变更积分');
        if (empty($reason)) adminReturn(2, '请输入变更原因');

        Db::startTrans();
        try {
            $time = time();
            $old_integral = Db::name('user')->where(['id' => $id])->value('integral');
            $do_user_id = session('id');
            // 新增余额变更记录
            $data = [
                'do_user_id' => $do_user_id,
                'user_id' => $id,
                'type' => $type,
                'old_integral' => $old_integral,
                'integral' => $integral,
                'reason' => $reason,
                'create_time' => $time
            ];
            Db::name('integral_change')->insert($data);

            $integral_type = $type == 1 ? 9 : 10;

            // 新增余额记录
            $integral_data = [
                'user_id' => $id,
                'integral' => $type == 1 ? $integral : 0 - $integral,
                'type' => $integral_type,
                'create_time' => $time
            ];
            Db::name('integral_log')->insert($integral_data);

            // 变更用户余额
            if ($type == 1)
                Db::name('user')->where(['id' => $id])->setInc('integral', $integral);
            else
                Db::name('user')->where(['id' => $id])->setDec('integral', $integral);

            Db::commit();
            adminReturn(1, '变更积分成功');
        } catch (\Exception $e) {
            Db::rollback();
            adminReturn(2, '系统繁忙，请稍后再试' . $e);
        }
    }

    /**
     * 积分变更记录
     * */
    public function integralChangeList()
    {
        $input = Request()->param();

        $username = $input['username'];
        $mobile = $input['mobile'];
        $type = $input['type'];
        $start_time = $input['start_time'];
        $end_time = $input['end_time'];

        if (!empty($username)) $where["u.username"] = ["like", "%" . $username . "%"];
        if (!empty($mobile)) $where["u.mobile"] = ["like", "%" . $mobile . "%"];
        if (!empty($type)) $where['p.type'] = $type;

        if (!empty($start_time) && empty($end_time)) {
            $where["p.create_time"] = ["egt", strtotime($start_time)];
        } elseif (empty($start_time) && !empty($end_time)) {
            $where["p.create_time"] = ["elt", strtotime($end_time) + 60 * 60 * 24 - 1];
        } elseif (!empty($start_time) && !empty($end_time)) {
            $where["p.create_time"] = ['between', [strtotime($start_time), strtotime($end_time) + 60 * 60 * 24 - 1]];
        }

        $list = Db::name('integral_change p')->join('cater_user u', 'p.user_id = u.id', 'left')
            ->field('p.user_id,p.do_user_id,u.username,u.mobile,p.type,p.old_integral,p.integral,p.reason,p.create_time')
            ->where($where)
            ->order('p.create_time desc')
            ->paginate()->each(function ($val) {
                $username = Db::name('user')->where(['id' => $val['user_id']])->value('username');
                $val['username'] = $username;
                $do_username = Db::name('user')->where(['id' => $val['do_user_id']])->value('username');
                $val['do_username'] = $do_username;

                return $val;
            });
        $this->assign('list', $list);

        $this->assign('title', '积分变更记录');
        return $this->view->fetch();
    }

    /**
     * 充值记录
     * */
    public function rechargeList()
    {
        $input = Request()->param();

        $username = $input['username'];
        $mobile = $input['mobile'];
        $start_time = $input['start_time'];
        $end_time = $input['end_time'];

        $where['b.type'] = 1;

        if (!empty($username)) $where["u.username"] = ["like", "%" . $username . "%"];
        if (!empty($mobile)) $where["u.mobile"] = ["like", "%" . $mobile . "%"];

        if (!empty($start_time) && empty($end_time)) {
            $where["b.create_time"] = ["egt", strtotime($start_time)];
        } elseif (empty($start_time) && !empty($end_time)) {
            $where["b.create_time"] = ["elt", strtotime($end_time) + 60 * 60 * 24 - 1];
        } elseif (!empty($start_time) && !empty($end_time)) {
            $where["b.create_time"] = ['between', [strtotime($start_time), strtotime($end_time) + 60 * 60 * 24 - 1]];
        }

        $list = Db::name('balance_log b')->join('cater_user u', 'b.user_id = u.id', 'left')
            ->field('b.id,b.balance,b.create_time,u.username,u.mobile')
            ->where($where)->order('b.create_time desc')
            ->paginate();

        $this->assign('list', $list);

        $this->assign('title', '充值记录');
        return $this->view->fetch();
    }

    /**
     * 返利记录
     * */
    public function returnIntegralList()
    {
        $input = Request()->param();

        $username = $input['username'];
        $mobile = $input['mobile'];
        $type = $input['type'];
        $start_time = $input['start_time'];
        $end_time = $input['end_time'];

        if (!empty($username)) $where["u.username"] = ["like", "%" . $username . "%"];
        if (!empty($mobile)) $where["u.mobile"] = ["like", "%" . $mobile . "%"];
        if (!empty($type)) {
            $where["i.type"] = $type;
        } else {
            $where['i.type'] = ['IN', [1, 2, 3]];
        }

        if (!empty($start_time) && empty($end_time)) {
            $where["i.create_time"] = ["egt", strtotime($start_time)];
        } elseif (empty($start_time) && !empty($end_time)) {
            $where["i.create_time"] = ["elt", strtotime($end_time) + 60 * 60 * 24 - 1];
        } elseif (!empty($start_time) && !empty($end_time)) {
            $where["i.create_time"] = ['between', [strtotime($start_time), strtotime($end_time) + 60 * 60 * 24 - 1]];
        }

        $list = Db::name('integral_log i')->join('cater_user u', 'i.user_id = u.id', 'left')
            ->field('i.id,i.order_id,i.integral,i.type,i.create_time,u.username,u.mobile')
            ->where($where)->order('i.create_time desc')
            ->paginate()->each(function ($v) {
                switch ($v['type']) {
                    case 1:
                        $type_desc = '下单得积分';
                        break;
                    case 2:
                        $type_desc = '积分兑换商品';
                        break;
                    case 3:
                        $type_desc = '退款返还积分';
                        break;
                    case 4:
                        $type_desc = '（积分兑换商品）退款返还积分';
                        break;
                }
                $v['type_desc'] = $type_desc;

                $order_username = '';
                if ($order_id = $v['order_id']) {
                    $user_id = Db::name('order')->where(['id' => $order_id])->value('user_id');
                    $order_username = Db::name('user')->where(['id' => $user_id ? : 0])->value('username');
                }
                $v['order_username'] = $order_username ? : '';

                return $v;
            });

        $this->assign('list', $list);

        $this->assign('title', '返利记录');
        return $this->view->fetch();
    }

    /**
     * 用户 启用/禁用
     * */
    public function doUserStatus()
    {
        $input = Request()->param();

        $id = $input['id'];
        $status = $input['status'];

        if (empty($id)) adminReturn(2, '用户ID缺失');
        if (empty($status)) adminReturn(2, '状态错误');

        $data = [
            'status' => $status,
            'update_time' => time()
        ];

        $res = Db::name('user')->where(['id' => $id])->update($data);
        if ($res) {
            adminReturn(1, '操作成功', url('userList'));
        } else {
            adminReturn(2, '操作失败');
        }
    }

    /**
     * 文章分类列表
     * */
    public function articleTypeList()
    {
        $list = Db::name('article_type')->paginate();

        $this->assign('list', $list);
        $this->assign('title', '文章分类列表');
        return $this->view->fetch();
    }

    /**
     * 新增/编辑 文章分类
     * */
    public function doArticleType()
    {
        if (Request()->isPost()) {
            $input = Request()->param();

            $id = $input['id'];
            $name = $input['name'];

            if (empty($name)) adminReturn(2, '请输入名称');

            $where['name'] = $name;
            if ($id) $where['id'] = ['neq', $id];
            $count = Db::name('article_type')->where($where)->count();
            if ($count > 0) adminReturn(2, '该分类已存在');

            $data = [
                'name' => $name
            ];

            if ($id > 0) {
                $res = Db::name('article_type')->where(['id' => $id])->update($data);
                if ($res) {
                    adminReturn(1, '编辑文章分类成功', url('articleTypeList'));
                } else {
                    adminReturn(2, '编辑失败或未编辑');
                }
            } else {
                $res = Db::name('article_type')->insert($data);
                if ($res) {
                    adminReturn(1, '新增文章分类成功', url('articleTypeList'));
                } else {
                    adminReturn(2, '新增文章分类失败');
                }
            }
        } else {
            $id = Request()->param('id');

            if ($id) $info = Db::name('article_type')->where(['id' => $id])->find();

            $this->assign('info', $info);
            $this->assign('title', ($id ? '编辑' : '新增') . '文章分类');

            return $this->view->fetch();
        }
    }

    /**
     * 删除文章分类
     * */
    public function delArticleType()
    {
        $id = Request()->param('id');

        if (empty($id)) adminReturn(2, '分类ID缺失');

        $info = Db::name('article_type')->where(['id' => $id])->find();
        if ($info) {
            $res = Db::name('article_type')->where(['id' => $id])->delete();
            if ($res) {
                adminReturn(1, '删除成功');
            } else {
                adminReturn(2, '删除失败');
            }
        } else {
            adminReturn(2, '数据不存在或已删除');
        }
    }

    /**
     * 文章列表
     * */
    public function articleList()
    {
        $input = Request()->param();

        $title = $input['title'] ? : '';

        $shop_id = session('shop_id');

        if ($title) $where['title'] = ['like', '%' . $title . '%'];
        if ($shop_id) $where['shop_id'] = $shop_id;

        $list = Db::name('article')->where($where)->order('sort asc, id desc')->paginate();

        $this->assign('list', $list);
        $this->assign('title', '文章列表');

        return $this->view->fetch();
    }

    /**
     * 新增/编辑 文章
     * */
    public function doArticle()
    {
        if (Request()->isPost()) {
            $input = Request()->param();

            $id = $input['id'];
            $title = $input['title'];
            $content = $input['content'];
            $shop_id = session('shop_id');

            if (empty($title)) adminReturn(2, '请输入标题');
            if (empty($content)) adminReturn(2, '请输入内容');

            if ($id) $where['id'] = ['neq', $id];
            $count = Db::name('article')->where(['shop_id' => $shop_id, 'title' => $title])->where($where)->count();
            if ($count) adminReturn(2, '文章标题已存在');

            $time = time();
            $data = [
                'shop_id' => $shop_id,
                'title' => $title,
                'content' => $content
            ];

            if ($id > 0) {
                //编辑
                $data['update_time'] = $time;

                $res = Db::name('article')->where(['id' => $id])->update($data);
                if ($res) {
                    adminReturn(1, '编辑成功', url('articleList'));
                } else {
                    adminReturn(2, '编辑失败');
                }
            } else {
                //新增
                $data['create_time'] = $time;

                $res = Db::name('article')->insert($data);
                if ($res) {
                    adminReturn(1, '新增成功', url('articleList'));
                } else {
                    adminReturn(2, '新增失败');
                }
            }
        } else {
            $id = Request()->param('id');

            if ($id > 0) {
                $info = Db::name('article')->where(['id' => $id])->find();
            }

            $this->assign('title', ($id > 0 ? '编辑' : '新增') . '文章');
            $this->assign('info', $info);

            return $this->view->fetch();
        }
    }

    /**
     * 删除文章
     * */
    public function delArticle()
    {
        $id = Request()->param('id');

        if (empty($id)) adminReturn(2, '文章ID缺失');

        $info = Db::name('article')->where(['id' => $id])->find();
        if ($info) {
            $res = Db::name('article')->where(['id' => $id])->delete();
            if ($res) {
                adminReturn(1, '删除成功');
            } else {
                adminReturn(2, '删除失败');
            }
        } else {
            adminReturn(2, '数据不存在或已删除');
        }
    }

    /**
     * 规格-属性 列表
     * */
    public function skuList()
    {
        $shop_id = session('shop_id');

        $where = [];
        if ($shop_id) $where['shop_id'] = $shop_id;

        $list = Db::name('sku')->where($where)->select();
        if ($list) {
            foreach ($list as &$v) {
                $v['shop_name'] = getShopName($v['shop_id']);
            }
        }
        $this->assign('list', json_encode($list, JSON_UNESCAPED_UNICODE));

        $this->assign('title', '规格-属性');
        return $this->fetch();
    }

    /**
     * 新增/编辑 规格-属性
     * */
    public function doSku()
    {

        if (Request()->isPost()) {
            $input = Request()->param();

            $shop_id = session('shop_id') ? : 0;

            $id = $input['id'];
            $pid = $input['pid'];
            $name = $input['name'];

            if (empty($name)) apiReturn(2, '请输入名称');

            if ($id) {
                $where['name'] = $name;
                $where['id'] = ['neq', $id];
                if ($pid) {
                    $where['pid'] = $pid;
                } else {
                    $where['pid'] = 0;
                }
                if ($shop_id) $where['shop_id'] = $shop_id;
                $count = Db::name('sku')->where($where)->count();

                $obj = $pid ? '属性' : '规格';
                if ($count > 0) apiReturn(2, '该' . $obj . '名称已存在');

                //编辑
                $data = [
                    'name' => $name,
                    'pid' => $pid,
                ];

                $res = Db::name('sku')->where(['id' => $id])->cache('sku')->update($data);
                if ($res) {
                    apiReturn(1, '编辑成功');
                } else {
                    apiReturn(2, '编辑失败');
                }
            } else {
                $where['name'] = $name;
                if ($pid) {
                    $where['pid'] = $pid;
                } else {
                    $where['pid'] = 0;
                }
                if ($shop_id) $where['shop_id'] = $shop_id;

                $count = Db::name('sku')->where($where)->count();

                $obj = $pid ? '属性' : '规格';
                if ($count > 0) apiReturn(2, '该' . $obj . '名称已存在');

                //新增
                $data = [
                    'name' => $name,
                    'pid' => $pid,
                ];
                if ($shop_id) $data['shop_id'] = $shop_id;

                $res = Db::name('sku')->insert($data);
                if ($res) {
                    cache('sku', null);
                    apiReturn(1, '新增成功');
                } else {
                    apiReturn(2, '新增失败');
                }
            }
        } else {
            $id = Request()->param('id');

            if ($id) {
                $info = Db::name('sku')->where(['id' => $id])->find();
            } else {
                $info = [];
            }

            $sku_list = Db::name('sku')->where(['pid' => 0])->select();

            $data = [
                'info' => $info,
                'sku_list' => $sku_list
            ];

            apiReturn(1, '获取数据成功', $data);
        }

    }

    /**
     * 删除 规格-属性
     * */
    public function delSku()
    {
        $input = Request()->param();

        $id = $input['id'];
        $pid = $input['pid'];

        $obj = $pid ? '属性' : '规格';
        if (empty($id)) apiReturn(2, $obj . 'ID缺失');

        Db::startTrans();
        try {
            Db::name('sku')->where(['id' => $id])->cache('sku')->delete();
            if ($pid == 0) Db::name('sku')->where(['pid' => $id])->delete();

            Db::commit();
            apiReturn(1, '删除成功');
        } catch (\Exception $e) {
            Db::rollback();
            apiReturn(2, '系统繁忙，请稍后再试~');
        }
    }

    /**
     * 商品分类列表
     * */
    public function goodsTypeList()
    {
        $shop_id = session('shop_id');

        $where = [];

        if ($shop_id) $where['shop_id'] = $shop_id;

        $list = Db::name('goods_type')->where($where)->order('sort asc')->select();
        if ($list) {
            foreach ($list as &$v) {
                $v['img_path'] = getPicture($v['img']);
                $v['shop_name'] = getShopName($v['shop_id']);
            }
        }

        $this->assign('sort_list', $list);
        $this->assign('list', json_encode($list, JSON_UNESCAPED_UNICODE));
        $this->assign('title', '商品分类列表');
        return $this->view->fetch();
    }

    /**
     * 新增/编辑 商品分类
     * */
    public function doGoodsType()
    {
        if (Request()->isPost()) {
            $input = Request()->param();

            $id = $input['id'];
            $img = $input['img'];
            $name = $input['name'];

            $shop_id = session('shop_id');

            if (empty($name)) adminReturn(2, '请输入名称');
            if (empty($img)) adminReturn(2, '请上传分类图片');

            $where['name'] = $name;
            if ($id) $where['id'] = ['neq', $id];
            $count = Db::name('goods_type')->where($where)->count();
            if ($count > 0) adminReturn(2, '该分类已存在');

            $data = [
                'name' => $name,
                'img' => $img
            ];

            if ($shop_id) $data['shop_id'] = $shop_id;

            if ($id > 0) {
                $res = Db::name('goods_type')->where(['id' => $id])->update($data);
                if ($res) {
                    adminReturn(1, '编辑商品分类成功', url('goodsTypeList'));
                } else {
                    adminReturn(2, '编辑失败或未编辑');
                }
            } else {
                $res = Db::name('goods_type')->insert($data);
                if ($res) {
                    adminReturn(1, '新增商品分类成功', url('goodsTypeList'));
                } else {
                    adminReturn(2, '新增商品分类失败');
                }
            }
        } else {
            $id = Request()->param('id');

            if ($id) $info = Db::name('goods_type')->where(['id' => $id])->find();

            $this->assign('info', $info);
            $this->assign('title', ($id ? '编辑' : '新增') . '商品分类');

            return $this->view->fetch();
        }
    }

    /**
     * 删除商品分类
     * */
    public function delGoodsType()
    {
        $input = Request()->param();

        $id = $input['id'];
        $pid = $input['pid'];

        if (empty($id)) adminReturn(2, '分类ID缺失');

        Db::startTrans();
        try {
            $info = Db::name('goods_type')->where(['id' => $id])->find();
            if ($info) {
                Db::name('goods_type')->where(['id' => $id])->delete();
                if ($pid == 0) Db::name('goods_type')->where(['pid' => $id])->delete();

                Db::commit();
                adminReturn(1, '删除成功');
            } else {
                Db::rollback();
                adminReturn(2, '数据不存在或已删除');
            }
        } catch (\Exception $e) {
            Db::rollback();
            adminReturn(2, '系统繁忙，请稍后再试~');
        }
    }


    /**
     * 网站配置排序
     * */
    public function saveGoodsTypeSort()
    {
        if (Request()->isPost()) {
            $input = Request()->param();

            $sortObj = json_decode($input['sortObj'], true);
            $res = model('GoodsType')->saveAll($sortObj);
            if ($res) {
                adminReturn(1, '更新排序成功');
            } else {
                adminReturn(2, '更新排序失败');
            }
        }
    }

    /**
     * 运费模板
     * */
    public function freightList()
    {
        $list = Db::name('freight')->paginate();


        $this->assign('list', $list);
        $this->assign('title', '运费模板');
        return $this->view->fetch();
    }

    /**
     * 新增/编辑 运费模板
     * */
    public function doFreight()
    {
        if (Request()->isPost()) {
            $input = Request()->param();

            $id = $input['id'];
            $name = $input['name'];
            $type = $input['type'];
            $init_count = $input['init_count'];
            $init_count_price = $input['init_count_price'];
            $inc_count = $input['inc_count'];
            $inc_count_price = $input['inc_count_price'];
            $init_weight = $input['init_weight'];
            $init_weight_price = $input['init_weight_price'];
            $inc_weight = $input['inc_weight'];
            $inc_weight_price = $input['inc_weight_price'];
            $diff_freight = $input['diff_freight'];

            if (empty($name)) apiReturn(2, '请输入模板名称');

            $where['name'] = $name;
            if ($id > 0) $where['id'] = ['neq', $id];
            $count = Db::name('freight')->where($where)->count();
            if ($count > 0) adminReturn(2, '模板名称已存在');


            if (($type == 1 && (empty($init_count) || empty($init_count_price) || empty($inc_count) || empty($inc_count_price)))
                ||
                ($type == 2 && (empty($init_weight) || empty($init_weight_price) || empty($inc_weight) || empty($inc_weight_price)))
            ) adminReturn(2, '请完善计价规格');

            $time = time();
            $data = [
                'name' => $name,
                'type' => $type,
                'init_count' => $init_count,
                'init_count_price' => $init_count_price,
                'inc_count' => $inc_count,
                'inc_count_price' => $inc_count_price,
                'init_weight' => $init_weight,
                'init_weight_price' => $init_weight_price,
                'inc_weight' => $inc_weight,
                'inc_weight_price' => $inc_weight_price,
                'diff_freight' => $diff_freight,
            ];

            if ($id > 0) {
                // 编辑
                $data['update_time'] = $time;
                $res = Db::name('freight')->where(['id' => $id])->update($data);
                if ($res) {
                    adminReturn(1, '编辑成功', url('freightList'));
                } else {
                    adminReturn(2, '编辑失败');
                }
            } else {
                // 新增
                $data['create_time'] = $time;
                $res = Db::name('freight')->insert($data);
                if ($res) {
                    adminReturn(1, '新增成功', url('freightList'));
                } else {
                    adminReturn(2, '新增失败');
                }
            }
        } else {
            $id = Request()->param('id');

            if ($id) $info = Db::name('freight')->where(['id' => $id])->find();

            $province_list = Db::name('province')->field('province_id,name province_name')->select();
            if ($province_list) {
                foreach ($province_list as &$v) {
                    $city_list = Db::name('city')->field('city_id,name city_name')->where(['province_id' => $v['province_id']])->select();
                    $v['city_list'] = $city_list;
                }
            }

            $info['diff_freight_list'] = json_decode($info['diff_freight'], true);
            $this->assign('diff_freight_data', $info['diff_freight'] ? $info['diff_freight'] : json_encode([]));
            $this->assign('info', $info);
            $this->assign('province_list', $province_list);
            $this->assign('title', ($id ? '编辑' : '新增') . '运费模板');
            return $this->view->fetch();
        }
    }

    /**
     * 服务保障
     * */
    public function serviceGuarantee()
    {
        if (Request()->isPost()) {
            $service_guarantee = Request()->param('service_guarantee');

            $res = Db::name('goods_service_guarantee')->where(' 1 = 1 ')->setField(['service_guarantee' => $service_guarantee]);
            if ($res) {
                adminReturn(1, '保存成功');
            } else {
                adminReturn(2, '保存失败');
            }
        } else {
            $service_guarantee = Db::name('goods_service_guarantee')->value('service_guarantee');

            $this->assign('service_guarantee', json_decode($service_guarantee, true));
            $this->assign('title', '服务保障');
            return $this->view->fetch();
        }
    }

    /**
     * 商品列表
     * */
    public function goodsList()
    {
        $input = Request()->param();

        $shop_id = session('shop_id');

        $one_type_id = $input['one_type_id'];
        $upper = $input['upper'];

        if ($one_type_id) $where['one_type_id'] = $one_type_id;
        if ($upper) $where['upper'] = $upper;
        if ($shop_id) $where['shop_id'] = $shop_id;

        $list = Db::name('goods')->where($where)->order('create_time desc')->paginate()->each(function ($item) {
            $item['one_type_name'] = Db::name('goods_type')->where(['id' => $item['one_type_id']])->value('name');

            return $item;
        });
        $this->assign('list', $list);

        $type_list = Db::name('goods_type')->order('sort asc')->select();
        $this->assign('type_list', $type_list);

        $this->assign('title', '商品列表');
        return $this->fetch();
    }

    /**
     * 新增/编辑 商品
     * */
    public function doGoods()
    {
        if (Request()->isPost()) {
            $input = Request()->param();

            Db::startTrans();
            try {
                //参数处理
                parse_str($input['form'], $form);

                $price_arr = [];
                if ($form['skus']) {
                    foreach ($form['skus'] as $v) {
                        if ($v['status'] == 1) $price_arr[] = $v['price'];
                    }
                }

                $min_price = min($price_arr);
                $max_price = max($price_arr);

                $skus = $form['skus'];

                if ($skus) {
                    foreach ($skus as $v) {
                        //                        if ($v['cost_price'] <= 0) adminReturn(2, '请完善成本价');
                        //                        if ($v['market_price'] <= 0) adminReturn(2, '请完善市场价');
                        if ($v['price'] <= 0) adminReturn(2, '请完善销售价');
                        if ($v['pay_integral'] <= 0) adminReturn(2, '请完善兑换积分');
                    }
                }
                unset($form['skus']);

                $id = $form['id'];

                if (empty($form['name'])) adminReturn(2, '请输入商品名称');
                if (empty($form['img'])) adminReturn(2, '请上传封面图');
                if (empty($form['one_type_id'])) adminReturn(2, '请选择所属分类');
                if (empty($form['stock_count'])) adminReturn(2, '请输入商品每日库存');
                if (empty($form['content'])) adminReturn(2, '请输入商品介绍');
                $time = time();

                $sort_ids = $input['sort_ids'];
                if ($sort_ids) {
                    Db::name('goods_sku')->where(['id' => ['IN', $sort_ids]])->setField('sort', 0);
                    $sort_ids_arr = explode(',', $sort_ids);
                    foreach ($sort_ids_arr as $k => $v) {
                        Db::name('goods_sku')->where(['id' => $v])->setField('sort', $k + 1);
                    }
                }

                $data = [
                    'name' => $form['name'],
                    'img' => $form['img'],
                    'imgs' => $form['imgs'],
                    'one_type_id' => $form['one_type_id'],
                    'limit_buy_count' => $form['limit_buy_count'],
                    'skus' => $input['skus'],
                    'min_price' => $min_price >= 0 ? $min_price : 0,
                    'max_price' => $max_price >= 0 ? $max_price : 0,
                    'upper' => $form['upper'],
                    'is_recommend' => $form['is_recommend'],
                    'copy_stock_count' => $form['stock_count'],
                    'stock_count' => $form['stock_count'],
                    'pack_price' => $form['pack_price'],
                    'delivery_price' => $form['delivery_price'],
                    'content' => $form['content'],
                    'sku_key' => $input['sku_key']
                ];

                $shop_id = session('shop_id');
                if ($shop_id) $data['shop_id'] = $shop_id;

                if ($id > 0) {
                    //编辑
                    $data['update_time'] = $time;

                    Db::name('goods')->where(['id' => $id])->update($data);

                    Db::name('sku_value')->where(['goods_id' => $id])->delete();

                    if ($skus) {
                        $sku_value = [];
                        foreach ($skus as $sku_id => &$v) {
                            $v['sku_id'] = $sku_id;
                            $v['goods_id'] = $id;

                            if ($v['picture']) {
                                $picture_info = Db::name('picture')->where(['path' => $v['picture']])->find();
                                if ($picture_info) $v['img'] = $picture_info['id'];
                            } else {
                                $v['img'] = 0;
                            }
                            unset($v['picture']);

                            $sku_value[] = $v;
                        }

                        Db::name('sku_value')->insertAll($sku_value);
                    }

                    Db::commit();
                    adminReturn(1, '编辑商品成功', url('goodsList'));
                } else {
                    //新增
                    $data['create_time'] = $time;

                    $goods_id = Db::name('goods')->insertGetId($data);

                    if ($skus) {
                        $sku_value = [];
                        foreach ($skus as $sku_id => &$v) {
                            $v['sku_id'] = $sku_id;
                            $v['goods_id'] = $goods_id;

                            if ($v['picture']) {
                                $picture_info = Db::name('picture')->where(['path' => $v['picture']])->find();
                                if ($picture_info) $v['img'] = $picture_info['id'];
                            } else {
                                $v['img'] = 0;
                            }
                            unset($v['picture']);

                            $sku_value[] = $v;
                        }

                        Db::name('sku_value')->insertAll($sku_value);
                    }

                    Db::commit();
                    adminReturn(1, '新增商品成功', url('goodsList'));
                }
            } catch (\Exception $e) {
                Db::rollback();
                adminReturn(2, '系统繁忙，请稍后再试~' . $e);
            }
        } else {
            $id = Request()->param('id');

            $info = Db::name('goods')->where(['id' => $id])->find();
            $info['imgs_arr'] = doImgs($info['imgs']);

            $this->assign('title', $id ? '编辑商品' : '新增商品');

            // 商品sku唯一标识
            if ($info['sku_key']) {
                $sku_key = $info['sku_key'];
            } else {
                $sku_key = uniqid();

                $parent_sku_list = Db::name('sku')->where(['pid' => 0])->order('id asc')->select();
                if ($parent_sku_list) {
                    foreach ($parent_sku_list as $v) {
                        $parent_sku_data = [
                            'name' => $v['name'],
                            'sku_key' => $sku_key
                        ];
                        $pid = Db::name('goods_sku')->insertGetId($parent_sku_data);

                        $son_sku_list = Db::name('sku')->where(['pid' => $v['id']])->order('id asc')->select();
                        if ($son_sku_list) {
                            $son_sku_data = [];
                            foreach ($son_sku_list as &$val) {
                                $son_sku_data[] = [
                                    'pid' => $pid,
                                    'name' => $val['name'],
                                    'sku_key' => $sku_key
                                ];
                            }
                            Db::name('goods_sku')->insertAll($son_sku_data);
                        }
                    }
                }
            }
            $this->assign('sku_key', $sku_key);

            $sku_list = Db::name('goods_sku')->field('id,name title')->where(['sku_key' => $sku_key, 'pid' => 0])->order('sort asc')->select();
            if ($sku_list) {
                //$skus_id_arr：所有属性的id集合
                $skus_id_arr = [];

                foreach ($sku_list as &$v) {
                    if ($id > 0) {
                        $sku_value_list = Db::name('sku_value')->field('sku_id')->where(['goods_id' => $id])->select();

                        if ($sku_value_list) {
                            foreach ($sku_value_list as &$val) {
                                $sku_id = explode('-', $val['sku_id']);
                                if ($sku_id) {
                                    foreach ($sku_id as &$value) {
                                        if (!in_array($value, $skus_id_arr)) {
                                            $skus_id_arr[] = $value;
                                        }
                                    }
                                }
                            }
                        }

                        $parent_list = Db::name('goods_sku')->distinct(true)->field('pid')->where(['id' => ['IN', $skus_id_arr], 'sku_key' => $sku_key])->select();
                        $parent_ids = array_column($parent_list, 'pid');

                        $v['checked'] = false;
                        if (in_array($v['id'], $parent_ids)) $v['checked'] = true;
                    } else {
                        $v['checked'] = false;
                    }

                    $child = Db::name('goods_sku')->field('id,name title')->where(['pid' => $v['id'], 'sku_key' => $sku_key])->select();
                    if ($child) {
                        foreach ($child as &$val) {
                            $val['checked'] = in_array($val['id'], $skus_id_arr) ? true : false;
                        }
                    }
                    $v['child'] = $child;
                }
            }

            $type_list = Db::name('goods_type')->order('sort asc')->select();
            $this->assign('type_list', $type_list);

            $this->assign('info', $info);
            $this->assign('sku_list', json_encode($sku_list, JSON_UNESCAPED_UNICODE));
            return $this->fetch();
        }
    }

    /**
     * 删除商品
     * */
    public function delGoods()
    {
        $id = Request()->param('id');

        if (empty($id)) adminReturn(2, '商品ID缺失');

        $info = Db::name('goods')->where(['id' => $id])->find();
        if ($info) {
            $res = Db::name('goods')->where(['id' => $id])->delete();
            if ($res) {
                adminReturn(1, '删除成功');
            } else {
                adminReturn(2, '删除失败');
            }
        } else {
            adminReturn(2, '数据不存在或已删除');
        }
    }

    /**
     * 套餐列表
     */
    public function mealList()
    {
        $list = Db::name('meal')->paginate();

        $this->assign('list', $list);
        $this->assign('title', '套餐列表');

        return $this->view->fetch();
    }


    /**
     * 新增/编辑 套餐
     * */
    public function doMeal()
    {
        if (Request()->isPost()) {
            $input = Request()->param();

            $id = $input["id"];
            $img = $input["img"];
            $imgs = $input["imgs"];
            $name = $input["name"];
            $price = $input['price'];
            $main_goods_name = $input["main_goods_name"];
            $main_goods_count = $input["main_goods_count"];
            $valid_day = $input["valid_day"];
            $main_goods_integral = $input["main_goods_integral"];
            $minor_goods_name = $input["minor_goods_name"];
            $minor_goods_integral = $input["minor_goods_integral"];
            $minor_get_cycle = $input["minor_get_cycle"];
            $minor_get_day = $input["minor_get_day"];
            $minor_get_count = $input["minor_get_count"];
            $upper = $input["upper"];
            $content = $input["content"];


            if (empty($img)) adminReturn(2, "请上传封面图");
            if (empty($imgs)) adminReturn(2, "请上传轮播图");
            if (empty($name)) adminReturn(2, "请输入券名称");
            if (empty($price)) adminReturn(2, "请输入价格");
            if (empty($main_goods_name)) adminReturn(2, "请输入主产品名称");
            if (empty($main_goods_count)) adminReturn(2, "请输入主产品数量");
            if (empty($valid_day)) adminReturn(2, "请输入有效期（天）");
            if (empty($main_goods_integral)) adminReturn(2, "请输入单个主产品可兑换积分");
            if (empty($minor_goods_name)) adminReturn(2, "请输入赠品名称");
            if (empty($minor_goods_integral)) adminReturn(2, "请输入单个赠品可兑换积分");
            if (empty($minor_get_day)) adminReturn(2, "请输入赠品领取周期（天）");
            if (empty($minor_get_cycle) || $minor_get_cycle <= 0) adminReturn(2, "请输入赠品领取期数");
            if (empty($minor_get_count) || $minor_get_count <= 0) adminReturn(2, "请输入赠品周期领取数量");

            $data = [
                "img" => $img,
                "imgs" => $imgs,
                "name" => $name,
                "price" => $price,
                "main_goods_name" => $main_goods_name,
                "main_goods_count" => $main_goods_count,
                "main_goods_integral" => $main_goods_integral,
                "valid_day" => $valid_day,
                "minor_goods_name" => $minor_goods_name,
                "minor_goods_count" => $minor_get_count * $minor_get_cycle,
                "minor_goods_integral" => $minor_goods_integral,
                "minor_get_day" => $minor_get_day,
                "minor_get_cycle" => $minor_get_cycle,
                "minor_get_count" => $minor_get_count,
                "upper" => $upper,
                "content" => $content
            ];

            if ($id > 0) {
                $data['update_time'] = time();
                $res = Db::name('meal')->where(['id' => $id])->update($data);
                if ($res) {
                    adminReturn(1, '编辑成功', url('mealList'));
                } else {
                    adminReturn(2, '编辑失败或未编辑');
                }
            } else {
                $data["create_time"] = time();
                $res = Db::name('meal')->insert($data);
                if ($res) {
                    adminReturn(1, '新增成功', url('mealList'));
                } else {
                    adminReturn(2, '新增失败');
                }
            }
        } else {
            $id = Request()->param('id');

            if ($id) $info = Db::name('meal')->where(['id' => $id])->find();
            $info['imgs_arr'] = doImgs($info['imgs']);

            $this->assign('info', $info);
            $this->assign('title', ($id ? '编辑' : '新增') . '套餐');

            return $this->view->fetch();
        }
    }

    /**
     * 设置充值
     * */
    public function setRecharge()
    {
        if (Request()->isPost()) {
            $recharge_guarantee = Request()->param('recharge_guarantee');

            $res = Db::name('recharge_guarantee')->where(' 1 = 1 ')->setField(['recharge_guarantee' => $recharge_guarantee]);
            if ($res) {
                adminReturn(1, '保存成功');
            } else {
                adminReturn(2, '保存失败');
            }
        } else {
            $recharge_guarantee = Db::name('recharge_guarantee')->value('recharge_guarantee');

            $this->assign('recharge_guarantee', json_decode($recharge_guarantee, true));
            $this->assign('title', '设置充值');
            return $this->view->fetch();
        }
    }


    /**
     * 领取记录
     * */
    public function receiveList()
    {
        $input = Request()->param();

        $status_code = $input['status_code'];
        $start_time = $input['start_time'];
        $end_time = $input['end_time'];
        $shop_id = $input['shop_id'];
        $user_id = $input['user_id'];

        if (!empty($start_time) && empty($end_time)) {
            $where["a.create_time"] = ["egt", strtotime($start_time)];
        } elseif (empty($start_time) && !empty($end_time)) {
            $where["a.create_time"] = ["elt", strtotime($end_time) + 60 * 60 * 24 - 1];
        } elseif (!empty($start_time) && !empty($end_time)) {
            $where["a.create_time"] = ['between', [strtotime($start_time), strtotime($end_time) + 60 * 60 * 24 - 1]];
        }

        if ($shop_id) {
            // 搜索门店
            $where['a.shop_id'] = $shop_id;
        } else {
            // 搜索区域
            $shop_list = Db::name('shop')->field('id')->where(['is_del' => 0])->select();
            $shop_ids = $shop_list ? array_column($shop_list, 'id') : [];
            if ($shop_ids) {
                $where['a.shop_id'] = ['IN', $shop_ids];
            } else {
                $where['a.shop_id'] = -1;
            }
        }

        if ($user_id) $where['a.user_id'] = $user_id;

        $where['a.type'] = 2;

        $list = Db::name('meal_consume a')->join('user b', "a.user_id = b.id", "left")
            ->field("a.*,b.mobile,b.username")
            ->where($where)->order('create_time desc')
            ->paginate()->each(
                function ($v) {
                    $shop_name = Db::name('shop')->where(['id' => $v['shop_id']])->value('name');
                    $v['shop_name'] = $shop_name ? : $v['shop_name'];

                    if ($v['pay_type'] == 1) {
                        $v['pay_type_text'] = "微信支付";
                    } elseif ($v['pay_type'] == 2) {
                        $v['pay_type_text'] = "积分兑换";
                    } else {
                        $v['pay_type_text'] = "未知";
                    }

                    return $v;
                }
            );
        $this->assign('list', $list);

        $all_pay_price = Db::name('order a')->join('user b', "a.user_id = b.id", "left")->where($where)->sum('pay_price');
        $this->assign('all_pay_price', sprintf('%.2f', $all_pay_price));

        $shop_list = Db::name('shop')->where(['is_del' => 0])->select();
        $this->assign('shop_list', $shop_list);

        $user_list = Db::name('user')->where(['is_admin' => 0, 'status' => 1])->select();
        $this->assign('user_list', $user_list);

        $this->assign('title', '领取记录');

        return $this->fetch();
    }

    /**
     * 优惠券设置
     */
    public function couponList()
    {
        $input = Request()->param();

        $name = $input['name'];
        $where["id"] = ["gt", 0];
        if ($name) $where['name'] = ["like", '%' . $name . '%'];
        $list = Db::name('coupon')->where($where)->order('create_time desc')->paginate();


        $this->assign('list', $list);

        $this->assign('title', '满减券列表');

        return $this->fetch();
    }

    /**
     * 新增/编辑 优惠券
     * */
    public function doCoupon()
    {
        if (Request()->isPost()) {
            $input = Request()->param();
            $id = $input["id"];
            $name = $input["name"];
            $full_price = $input["full_price"];
            $face_price = $input["face_price"];
            $use_day = $input["use_day"];

            if (empty($name)) adminReturn(2, "请输入券名称");
            if (empty($full_price)) adminReturn(2, "请输入消费到达金额");
            if (empty($face_price)) adminReturn(2, "请输入面值");
            if (empty($use_day)) adminReturn(2, "请输入有效期（天）");

            if ($full_price < 0) adminReturn(2, "消费到达金额不能小于0");
            if ($face_price < 0) adminReturn(2, "面值不能小于0");
            if ($use_day < 0) adminReturn(2, "有效期不能小于0");
            if ($full_price < $face_price) adminReturn(2, "消费到达金额不能小于面值");
            if (!preg_match("/^[1-9][0-9]*$/", $use_day)) adminReturn(2, "有效期只能是正整数");

            $data = [
                "name" => $name,
                "full_price" => $full_price,
                "face_price" => $face_price,
                "use_day" => $use_day,
            ];

            $shop_id = session('shop_id');
            if ($shop_id) $data['shop_id'] = $shop_id;

            if ($id > 0) {
                $res = Db::name('coupon')->where(['id' => $id])->update($data);
                if ($res) {
                    adminReturn(1, '编辑优惠券成功', url('couponList'));
                } else {
                    adminReturn(2, '编辑优惠券失败或未编辑');
                }
            } else {
                $data["create_time"] = time();
                $res = Db::name('coupon')->insert($data);
                if ($res) {
                    adminReturn(1, '新增优惠券成功', url('couponList'));
                } else {
                    adminReturn(2, '新增优惠券失败');
                }
            }
        } else {
            $id = Request()->param('id');

            if ($id) $info = Db::name('coupon')->where(['id' => $id])->find();

            $this->assign('info', $info);
            $this->assign('title', ($id ? '编辑' : '新增') . '优惠券');

            return $this->view->fetch();
        }
    }

    /**
     *删除优惠券
     */
    public function delCoupon()
    {
        $id = Request()->param('id');
        if (empty($id)) adminReturn(2, '参数丢失');
        $res_de_coupon = Db::name('coupon')->where(['id' => $id])->delete();
        if ($res_de_coupon) {
            adminReturn(1, '删除优惠券成功', url('deCoupon'));
        } else {
            adminReturn(2, '删除优惠券失败');
        }
    }

    /**
     * 领取记录
     * */
    public function getCouponUserList()
    {
        $input = Request()->param();

        $id = $input['id'];
        $status = $input['status'];

        $where['coupon_id'] = $id;
        $where['is_del'] = 0;
        if ($status) $where['status'] = $status;
        $list = Db::name('user_coupon')->where($where)->order('create_time desc')->paginate()->each(function ($v) {
            $username = Db::name('user')->where(['id' => $v['user_id']])->value('username');
            $v['username'] = $username ? : '';

            switch ($v['status']) {
                case 1:
                    $v['status_desc'] = '待使用';
                    break;
                case 2:
                    $v['status_desc'] = '已使用';
                    break;
                case 3:
                    $v['status_desc'] = '已过期';
                    break;
            }

            return $v;
        });

        $this->assign('list', $list);

        $this->assign('title', '领取记录');

        return $this->fetch();
    }

    /**
     * 门店列表
     * */
    public function shopList()
    {
        $shop_id = session('shop_id');

        if ($shop_id) $where['id'] = $shop_id;

        $list = Db::name('shop')->where(['is_del' => 0])->where($where)->paginate();

        $this->assign('list', $list);
        $this->assign('title', '门店列表');

        return $this->view->fetch();
    }

    /**
     * 新增/编辑 门店
     * */
    public function doShop()
    {
        if (Request()->isPost()) {
            $input = Request()->param();

            $id = $input["id"];
            $name = $input['name'];
            $mobile = $input['mobile'];
            $img = $input['img'];
            $lat = $input['lat'];
            $lng = $input['lng'];
            $address = $input['address'];

            $time = time();

            if (empty($name)) adminReturn(2, '请输入门店名称');
            if (empty($mobile)) adminReturn(2, '请输入门店电话');
            if (empty($lat) || empty($lng)) apiReturn(2, '请勾选地图下方列表地址之后再进行提交');

            if ($id) $where['id'] = ['neq', $id];
            $where['name'] = $name;
            $count = Db::name('shop')->where($where)->count();
            if ($count) adminReturn(2, '门店名称已存在');

            $data = [
                'name' => $name,
                'mobile' => $mobile,
                'img' => $img,
                'lat' => $lat,
                'lng' => $lng,
                'address' => $address
            ];

            if ($id > 0) {
                $data['update_time'] = $time;
                $res = Db::name('shop')->where(['id' => $id])->update($data);
            } else {
                $data['create_time'] = $time;
                $res = Db::name('shop')->insertGetId($data);
            }

            if ($res) {
                adminReturn(1, ($id ? '编辑' : '新增') . '成功', url('shopList'));
            } else {
                adminReturn(2, ($id ? '编辑' : '新增') . '成功');
            }
        } else {
            $id = Request()->param('id');

            if ($id) {
                $info = Db::name('shop')->where(['id' => $id])->find();
                if ($info['lat'] && $info['lng']) {
                    $map_url = 'https://apis.map.qq.com/tools/locpicker?type=1&search=1&policy=1&key=D4GBZ-7XF64-DQ5UN-KR24K-SY5YF-CZFSA&referer=myapp&coord=' . $info['lat'] . ',' . $info['lng'];
                } else {
                    $map_url = 'https://apis.map.qq.com/tools/locpicker?type=1&search=1&policy=1&key=D4GBZ-7XF64-DQ5UN-KR24K-SY5YF-CZFSA&referer=myapp';
                }
            } else {
                $map_url = 'https://apis.map.qq.com/tools/locpicker?type=1&search=1&policy=1&key=D4GBZ-7XF64-DQ5UN-KR24K-SY5YF-CZFSA&referer=myapp';
            }

            $this->assign('info', $info);
            $this->assign('map_url', $map_url);
            $this->assign('title', ($id ? '编辑' : '新增') . '门店');

            $user_list = Db::name('user')->where(['is_admin' => 0, 'status' => 1])->select();
            if ($user_list) {
                foreach ($user_list as &$v) {
                    $v['checked'] = in_array($v['id'], explode(',', $info['user_ids'])) ? 'checked' : '';
                }
            }
            $this->assign('user_list', $user_list);

            return $this->view->fetch();
        }
    }

    /**
     * 删除门店
     * */
    public function delShop()
    {
        $id = Request()->param('id');

        if (empty($id)) adminReturn(2, '门店ID缺失');

        $info = Db::name('shop')->where(['id' => $id])->find();
        if ($info) {
            $res = Db::name('shop')->where(['id' => $id])->setField('is_del', 1);
            if ($res) {
                adminReturn(1, '删除成功');
            } else {
                adminReturn(2, '删除失败');
            }
        } else {
            adminReturn(2, '数据不存在或已删除');
        }
    }

    /**
     * banner列表
     */
    public function bannerList()
    {
        $list = Db::name('banner')->order('id desc')->paginate();

        $this->assign('list', $list);
        $this->assign('title', 'banner列表');

        return $this->view->fetch();
    }

    /**
     * 新增/编辑 banner
     * */
    public function doBanner()
    {
        if (Request()->isPost()) {
            $input = Request()->param();

            $id = $input["id"];
            $img = $input["img"];
            $type = $input["type"];
            $to_id = $input["to_id"];

            if (empty($img)) adminReturn(2, '请上传banner图');
            if ($type == 1 && empty($to_id)) adminReturn(2, '请选择商品');
            if ($type == 2 && empty($to_id)) adminReturn(2, '请选择文章');

            $data = [
                "shop_id" => session('shop_id'),
                "img" => $img,
                "type" => $type,
                'to_id' => $to_id
            ];

            if ($id > 0) {
                $res = Db::name('banner')->where(['id' => $id])->update($data);
                if ($res) {
                    adminReturn(1, '编辑banner成功', url('bannerList'));
                } else {
                    adminReturn(2, '编辑banner失败或未编辑');
                }
            } else {
                $res = Db::name('banner')->insert($data);
                if ($res) {
                    adminReturn(1, '新增banner成功', url('bannerList'));
                } else {
                    adminReturn(2, '新增banner失败');
                }
            }
        } else {
            $id = Request()->param('id');

            if ($id) $info = Db::name('banner')->where(['id' => $id])->find();

            $goods_list = Db::name('goods')->field('id,name')->select();
            $this->assign('goods_list', $goods_list);
            $this->assign('goods_list_obj', json_encode($goods_list, JSON_UNESCAPED_UNICODE));

            $article_list = Db::name('article')->field('id,title name')->select();
            $this->assign('article_list_obj', json_encode($article_list, JSON_UNESCAPED_UNICODE));

            $this->assign('info', $info);
            $this->assign('title', ($id ? '编辑' : '新增') . 'banner');

            return $this->view->fetch();
        }
    }

    /**
     * 删除banner
     * */
    public function delBanner()
    {
        $id = Request()->param('id');

        if (empty($id)) adminReturn(2, 'bannerID缺失');

        $info = Db::name('banner')->where(['id' => $id])->find();
        if ($info) {
            $res = Db::name('banner')->where(['id' => $id])->delete();
            if ($res) {
                adminReturn(1, '删除成功');
            } else {
                adminReturn(2, '删除失败');
            }
        } else {
            adminReturn(2, '数据不存在或已删除');
        }
    }

    /**
     * 订单列表
     */
    public function orderList()
    {
        $input = Request()->param();

        $status = $input['status'];
        $after_status = $input['after_status'];
        $start_time = $input['start_time'];
        $end_time = $input['end_time'];
        $shop_id = session('shop_id');
        $order_sn = $input['order_sn'];

        if (!empty($status)) {
            $where["a.status"] = $status;
        } else {
            $where['a.status'] = ['neq', '7,8'];
        }
        if (!empty($after_status)) $where["a.after_status"] = $after_status;

        if (!empty($start_time) && empty($end_time)) {
            $where["a.create_time"] = ["egt", strtotime($start_time)];
        } elseif (empty($start_time) && !empty($end_time)) {
            $where["a.create_time"] = ["elt", strtotime($end_time) + 60 * 60 * 24 - 1];
        } elseif (!empty($start_time) && !empty($end_time)) {
            $where["a.create_time"] = ['between', [strtotime($start_time), strtotime($end_time) + 60 * 60 * 24 - 1]];
        }

        if ($shop_id) $where['a.shop_id'] = $shop_id;
        if ($order_sn) $where['a.order_sn'] = ['like', "%${order_sn}%"];

        //        $where['a.is_del'] = 0;
        $where['a.is_pay'] = 1;
        $where["a.id"] = ["gt", 0];
        $list = Db::name('order a')->field("a.*,b.username")->join('user b', "a.user_id = b.id", "left")->where($where)->order('create_time desc')->paginate()->each(
            function ($v) {
                $shop_info = Db::name('shop')->field('name,lat,lng')->where(['id' => $v['shop_id']])->find();
                $v['shop_name'] = $shop_info['name'] ? : '门店不存在';
                $v['distance'] = distance($v['get_lat'], $v['get_lng'], $shop_info['lat'], $shop_info['lng']);

                $v['status_text'] = doOrderStatus($v['status']);

                if ($v['after_status'] == 0) {
                    $v['after_status_text'] = "未售后";
                } elseif ($v['after_status'] == 1) {
                    $v['after_status_text'] = "售后中";
                } elseif ($v['after_status'] == 2) {
                    $v['after_status_text'] = "售后成功";
                } elseif ($v['after_status'] == 3) {
                    $v['after_status_text'] = "售后失败";
                } else {
                    $v['after_status_text'] = "未知";
                }

                if ($v['pay_type'] == 1) {
                    $v['pay_type_text'] = "微信支付";
                } elseif ($v['pay_type'] == 2) {
                    $v['pay_type_text'] = "积分兑换";
                } else {
                    $v['pay_type_text'] = "未知";
                }

                // 预约订单是否现在【开始配送】按钮
                $businessOrderShowSendBtn = $v['is_business'] == 0 || ($v['is_business'] == 1 && isTimeInRange(date('Y-m-d H:i'), $v['arrive_time'])) ? true : false;
                $v['businessOrderShowSendBtn'] = $businessOrderShowSendBtn;

                // 商品信息
                $vice_order_list = Db::name('vice_order')->field('name,count')->where(['order_id' => $v['id']])->select();
                $v['vice_order_list'] = $vice_order_list;

                return $v;
            }
        );

        $this->assign('list', $list);

        $all_pay_price = Db::name('order a')->join('user b', "a.user_id = b.id", "left")->where($where)->sum('pay_price');
        $this->assign('all_pay_price', sprintf('%.2f', $all_pay_price));

        $shop_list = Db::name('shop')->where(['is_del' => 0])->select();
        $this->assign('shop_list', $shop_list);

        $user_list = Db::name('user')->where(['is_admin' => 0, 'status' => 1])->select();
        $this->assign('user_list', $user_list);

        $this->assign('title', '订单列表');

        return $this->fetch();
    }

    /**
     * 导出订单
     * */
    public function exportOrderList()
    {
        $title = date('YmdHis') . '订单';
        $th = ['ID', '会员昵称', '订单号', '总金额', '支付金额', '预约用餐时间', '收货信息', '订单状态', '售后状态', '创建时间'];
        $td = ['id', 'username', 'order_sn', 'all_price', 'pay_price', 'status_text', 'after_status_text', 'create_time'];

        $input = Request()->param();

        $status = $input['status'];
        $after_status = $input['after_status'];
        $start_time = $input['start_time'];
        $end_time = $input['end_time'];
        $shop_id = $input['shop_id'];
        $user_id = $input['user_id'];

        if (!empty($status)) $where["a.status"] = $status;
        if (!empty($after_status)) $where["a.after_status"] = $after_status;

        if (!empty($start_time) && empty($end_time)) {
            $where["a.create_time"] = ["egt", strtotime($start_time)];
        } elseif (empty($start_time) && !empty($end_time)) {
            $where["a.create_time"] = ["elt", strtotime($end_time) + 60 * 60 * 24 - 1];
        } elseif (!empty($start_time) && !empty($end_time)) {
            $where["a.create_time"] = ['between', [strtotime($start_time), strtotime($end_time) + 60 * 60 * 24 - 1]];
        }

        if ($shop_id) {
            // 搜索门店
            $where['a.shop_id'] = $shop_id;
        } else {
            // 搜索区域
            $shop_list = Db::name('shop')->field('id')->where(['is_del' => 0])->select();
            $shop_ids = $shop_list ? array_column($shop_list, 'id') : [];
            if ($shop_ids) {
                $where['a.shop_id'] = ['IN', $shop_ids];
            } else {
                $where['a.shop_id'] = -1;
            }
        }

        if ($user_id) $where['a.user_id'] = $user_id;

        $where['a.is_del'] = 0;
        $where["a.id"] = ["gt", 0];
        $list = Db::name('order a')->field("a.*,b.mobile,b.username")->join('user b', "a.user_id = b.id", "left")->where($where)->order('create_time desc')->select();
        if ($list) {
            foreach ($list as &$v) {
                $shop_name = Db::name('shop')->where(['id' => $v['shop_id']])->value('name');
                $v['shop_name'] = $shop_name ? : '门店不存在';

                $v['status_text'] = doOrderStatus($v['status']);

                if ($v['after_status'] == 0) {
                    $v['after_status_text'] = "未售后";
                } elseif ($v['after_status'] == 1) {
                    $v['after_status_text'] = "售后中";
                } elseif ($v['after_status'] == 2) {
                    $v['after_status_text'] = "售后成功";
                } elseif ($v['after_status'] == 3) {
                    $v['after_status_text'] = "售后失败";
                } else {
                    $v['after_status_text'] = "未知";
                }

                if ($v['pay_type'] == 1) {
                    $v['pay_type_text'] = "微信支付";
                } elseif ($v['pay_type'] == 2) {
                    $v['pay_type_text'] = "积分兑换";
                } else {
                    $v['pay_type_text'] = "未知";
                }

                $v['create_time'] = timeFormat($v['create_time']);
            }
        }

        exportExcel($title, $th, $td, $list);
    }

    /**
     * 后台所有待配送订单一键配送
     * */
    public function allOrderSend()
    {
        $shop_id = session('shop_id');

        if (empty($shop_id)) adminReturn(2, '门店ID缺失');

        $time = time();

        $list = Db::name('order')->field('id,user_id,shop_id')->where(['is_pay' => 1, 'shop_id' => $shop_id, 'status' => 2, 'is_business' => 0, 'pay_time' => ['elt', $time]])->select();
        $business_list = Db::name('order')->field('id,user_id,shop_id,arrive_time')->where(['is_pay' => 1, 'shop_id' => $shop_id, 'status' => 2, 'is_business' => 1])->select();

        $ids = '';
        $data_msg = [];
        $time = time();

        Db::startTrans();
        try {
            if ($list) {
                foreach ($list as &$v) {
                    if ($ids == '') {
                        $ids = $v['id'];
                    } else {
                        $ids .= ',' . $v['id'];
                    }

                    $data_msg[] = [
                        "user_id" => $v["user_id"],
                        "shop_id" => $v['shop_id'],
                        "order_id" => $v['id'],
                        "title" => "您的订单已经开始配送",
                        "content" => "您的订单已经开始配送",
                        "create_time" => $time,
                    ];
                }
            }

            if ($business_list) {
                foreach ($business_list as &$v) {
                    if (isTimeInRange(date('Y-m-d H:i'), $v['arrive_time'])) {
                        if ($ids == '') {
                            $ids = $v['id'];
                        } else {
                            $ids .= ',' . $v['id'];
                        }

                        $data_msg[] = [
                            "user_id" => $v["user_id"],
                            "shop_id" => $v['shop_id'],
                            "order_id" => $v['id'],
                            "title" => "您的订单已经开始配送",
                            "content" => "您的订单已经开始配送",
                            "create_time" => $time,
                        ];
                    }
                }
            }

            if ($ids) {
                Db::name('order')->where(['id' => ['IN', $ids]])->update(['status' => 3, 'update_time' => $time]);

                Db::name("msg")->insertAll($data_msg);

                Db::commit();
                adminReturn(1, '一键配送成功');
            } else {
                Db::rollback();
                adminReturn(2, '没有需要配送的订单');
            }

        } catch (\Exception $e) {
            Db::rollback();
            adminReturn(2, '一键配送失败');
        }


    }

    /**
     * 订单改价
     * */
    public function changePayPrice()
    {
        $input = Request()->param();

        $id = $input['id'];
        $pay_price = $input['pay_price'];

        if (empty($id)) apiReturn(2, '订单ID缺失');
        if ($pay_price < 0) apiReturn(2, '金额输入有误，请重新输入');

        $res = Db::name('order')->where(['id' => $id])->setField('pay_price', $pay_price);
        if ($res) {
            apiReturn(1, '保存成功');
        } else {
            apiReturn(2, '保存失败');
        }
    }

    /**
     * 订单详情
     */
    public function doOrder()
    {
        if (Request()->isPost()) {
            $input = Request()->param();
            $id = $input["id"];

            $order_info = Db::name("order")->where(["id" => $id])->find();
            if ($order_info['status'] == 2) {
                // 开始配送
                $status = 3;
                Db::startTrans();
                $data = [
                    "status" => $status,
                ];

                $data['update_time'] = time();
                Db::name('order')->where(['id' => $id])->update($data);
                /** 添加发送消息 */
                $data_msg = [
                    "user_id" => $order_info["user_id"],
                    "shop_id" => $order_info['shop_id'],
                    "order_id" => $id,
                    "title" => "您的订单已经开始配送",
                    "content" => "您的订单已经开始配送",
                    "create_time" => time(),
                ];
                Db::name("msg")->insert($data_msg);

                /** 添加15天自动确认收货计划 */
                /*$time = time() + 24 * 3600 * C('CONFIRM_GET_DAY');
                $data_plan = [
                    "user_id" => $order_info["user_id"],
                    "order_id" => $id,
                    "type" => 2,
                    "execute_date" => date('Y-m-d', $time),
                ];
                Db::name("plan")->insert($data_plan);*/

                Db::commit();
                adminReturn(1, '操作成功', url('orderList'));
            } elseif ($order_info['status'] == 6) {
                $after_status = $input['after_status'];
                $after_refuse_reason = $input['after_refuse_reason'];
                if (empty($after_status)) adminReturn(2, '请选择售后操作');
                if ($after_status == 3 && empty($after_refuse_reason)) adminReturn(2, "请输入拒绝原因");

                $time = time();

                Db::startTrans();
                try {
                    $data = [
                        'back_order_sn' => $order_info['pay_order_sn'],
                        'status' => 7,//订单状态改成售后完成
                        'after_status' => $after_status,
                        'after_refuse_reason' => $after_refuse_reason,
                        'update_time' => $time
                    ];
                    Db::name('order')->where(['id' => $id])->update($data);

                    $price = $order_info['pay_price'];
                    if ($after_status == 2) {
                        // 同意售后

                        $vice_order_list = Db::name('vice_order')->where(['order_id' => $id])->select();
                        if ($vice_order_list) {
                            foreach ($vice_order_list as &$v) {
                                // 1：商品销售量减少
                                Db::name('goods')->where(['id' => $v['goods_id']])->setDec('sales_count', $v['count']);
                                // 2：商品库存增加
                                if ($order_info['is_business'] == 0 || date('Y-m-d') == explode(' ', $order_info['arrive_time'])[0]) Db::name('goods')->where(['id' => $v['goods_id']])->setInc('stock_count', $v['count']);
                            }
                        }

                        // 3：支付了金额，金额原路退回
                        if ($price > 0) {
                            Loader::import('wxsdk\wxPay', EXTEND_PATH);
                            $obj = new \wxPay();

                            $price = C('TEST_PAY') ? 0.01 : $price;
                            $obj->refund($price, $price, $order_info['pay_order_sn'], $order_info['pay_order_sn'], $order_info['after_reason']);
                        }

                        // 4：支付了积分，积分原路退回
                        if ($use_integral = $order_info['use_integral']) {
                            $integral_log = [
                                'user_id' => $order_info['user_id'],
                                'shop_id' => $order_info['shop_id'],
                                'integral' => $use_integral,
                                'type' => 4,
                                'order_id' => $id,
                                'create_time' => time()
                            ];
                            Db::name('integral_log')->insert($integral_log);
                        }

                        // 查询是否已经赠送积分
                        $is_send = Db::name('integral_log')->where(['order_id' => $id, 'type' => 1])->count();
                        // 5：赠送了积分，积分原路退回
                        if ($send_integral = $order_info['send_integral'] && $is_send) {
                            $integral_log = [
                                'user_id' => $order_info['user_id'],
                                'shop_id' => $order_info['shop_id'],
                                'integral' => 0 - $send_integral,
                                'type' => 3,
                                'order_id' => $id,
                                'create_time' => time()
                            ];
                            Db::name('integral_log')->insert($integral_log);
                        }

                        // 返还积分到客户账户
                        $custom_info = Db::name('customer')->where(['user_id' => $order_info['user_id'], 'shop_id' => $order_info['shop_id']])->find();
                        $custom_data = [
                            //                            'success_order_count' => $custom_info['success_order_count'] - 1,
                            'fail_order_count' => $custom_info['fail_order_count'] + 1,
                            'integral' => $custom_info['integral'] + $use_integral - $send_integral,
                            'update_time' => time()
                        ];
                        Db::name('customer')->where(['user_id' => $order_info['user_id'], 'shop_id' => $order_info['shop_id']])->update($custom_data);

                        // 6：使用了优惠券，优惠券原路退回
                        if ($user_coupon_id = $order_info['user_coupon_id']) {
                            Db::name('user_coupon')->where(['id' => $user_coupon_id])->setField('status', 1);
                        }

                        // 7：使用了实物券，实物券原路退回
                        if ($lottery_coupon_id = $order_info['lottery_coupon_id']) {
                            Db::name('user_lottery_coupon')->where(['id' => $lottery_coupon_id])->setField('is_use', 0);
                        }

                        // 8：站内消息
                        $msg_data = [
                            'user_id' => $order_info['user_id'],
                            'shop_id' => $order_info['shop_id'],
                            'order_id' => $id,
                            'title' => '退款成功',
                            'content' => '您有一笔售后订单退款成功',
                            'create_time' => time()
                        ];
                        Db::name('msg')->insert($msg_data);
                    } else if ($after_status == 3) {
                        // 拒绝售后
                        $order_data = [
                            'status' => 2,
                            'after_status' => $after_status,
                            'after_refuse_reason' => $input['after_refuse_reason'],
                            'update_time' => time()
                        ];
                        Db::name('order')->where(['id' => $id])->update($order_data);

                        // 站内消息
                        $msg_data = [
                            'user_id' => $order_info['user_id'],
                            'shop_id' => $order_info['shop_id'],
                            'order_id' => $id,
                            'title' => '退款失败',
                            'content' => '您有一笔售后订单退款失败，原因：' . $input['after_refuse_reason'],
                            'create_time' => time()
                        ];
                        Db::name('msg')->insert($msg_data);
                    }

                    Db::commit();
                    adminReturn(1, '操作成功', url('orderList'));
                } catch (\Exception $e) {
                    Db::rollback();
                    adminReturn(2, '系统繁忙，请稍后再试~');
                }
            }
        } else {
            $id = input("id");
            $order_info = Db::name('order a')->field("a.*,b.mobile,b.username")->where(["a.id" => $id])->join('user b', "a.user_id = b.id", "left")->find();
            $shop_info = Db::name('shop')->where(['id' => $order_info['shop_id']])->find();
            $order_info['distance'] = distance($order_info['get_lat'], $order_info['get_lng'], $shop_info['lat'], $shop_info['lng']);
            $order_vice = Db::name("vice_order")->where(["order_id" => $id])->select();
            foreach ($order_vice as &$vo) {
                $suk_value_arr = explode("-", $vo['sku_id']);
                $suk_name_str = "";
                foreach ($suk_value_arr as $vv) {
                    $sku_info = Db::name("goods_sku")->where(["id" => $vv])->find();
                    $sku_p_info = Db::name("goods_sku")->where(["id" => $sku_info['pid']])->find();
                    $suk_name_str .= $sku_p_info['name'] . ": " . $sku_info['name'] . ";";
                }
                $vo['suk_name_str'] = $suk_name_str;

                /** 查看商品是不是有评论 */
                $is_have = Db::name('goods_comment')->where(["order_id" => $id, "goods_id" => $vv['goods_id']])->value("id");
                if ($is_have) {
                    $is_comment = $is_have;
                } else {
                    $is_comment = 0;
                }
                $vo['is_comment'] = $is_comment;
            }

            $shop_name = Db::name('shop')->where(['id' => $order_info['shop_id']])->value('name');
            $order_info['shop_name'] = $shop_name ? : '门店不存在';

            $this->assign('info', $order_info);
            $this->assign('order_vice', $order_vice);

            $this->assign('title', '订单详情');
            return $this->fetch();
        }
    }

    /**
     *商品评论
     */
    public function doComment()
    {
        $input = Request()->param();
        $id = $input["id"];

        //查询出评论内容
        $info = Db::name('goods_comment')->where(["id" => $id])->find();

        $info["img_arr"] = explode(",", $info["imgs"]);

        $this->assign('info', $info);
        $this->assign('title', '评论详情');
        return $this->fetch();
    }

    /**
     * 活动设置
     * */
    public function setActivity()
    {
        $shop_id = session('shop_id');
        $this->assign('shop_id', $shop_id);
        if (Request()->isPost()) {
            $input = Request()->param();

            $id = $input['id'];
            $type = $input['type'];
            $full_price = $input['full_price'] ? : 0;
            $time = $input['time'];
            $lottery_coupon_ids = $input['lottery_coupon_ids'];

            if (empty($shop_id)) adminReturn(2, '门店ID缺失');
            if (empty($time)) adminReturn(2, '请选择活动时间段');
            $time_arr = explode(' - ', $time);
            if (strtotime($time_arr[0]) == strtotime($time_arr[1])) adminReturn(2, '开始时间和结束时间不能相同');
            if (strtotime($time_arr[0]) > strtotime($time_arr[1])) adminReturn(2, '开始时间不能大于结束时间');

            if (count($lottery_coupon_ids) < 3) adminReturn(2, '抽奖奖励请选择3-6个');

            if ($id) {
                $info = Db::name('activity')->where(['shop_id' => $shop_id, 'status' => ['neq', 2]])->order('id desc')->find();
                $info_time_arr = explode(' - ', $info['time']);
                if ($info['status'] == 1 && time() >= strtotime($info_time_arr[0]) && time() <= strtotime($info_time_arr[1])) adminReturn(2, '活动正在进行中，无法修改');
            }

            $lottery_coupon_list = Db::name('lottery_coupon')->field('img,name')->where(['shop_id' => $shop_id, 'id' => ['IN', $lottery_coupon_ids]])->select();
            if ($lottery_coupon_list) {
                foreach ($lottery_coupon_list as &$v) {
                    $v['img'] = getPicture($v['img']);
                }
            }

            $data = [
                'shop_id' => $shop_id,
                'type' => $type,
                'full_price' => $full_price,
                'add_price' => $type == 2 ? 1 : 0,
                'time' => $time,
                'lottery_coupon_ids' => implode(',', $lottery_coupon_ids),
            ];

            $time = time();
            if (empty($id)) {
                $data['create_time'] = $time;
                $res = Db::name('activity')->insert($data);
            } else {
                $data['update_time'] = $time;
                $res = Db::name('activity')->where(['id' => $id])->update($data);
            }

            if ($res) {
                adminReturn(1, '保存成功');
            } else {
                adminReturn(2, '保存失败');
            }
        } else {
            $info = Db::name('activity')->where(['shop_id' => $shop_id, 'status' => ['neq', 2]])->order('id desc')->find();

            $time_arr = explode(' - ', $info['time']);
            $time = time();
            if ($info['status'] == 1 && $time >= strtotime($time_arr[1])) {
                // 当前活动为开启状态，并且当前时间超出活动结束时间，将活动自动结束
                Db::name('activity')->where(['id' => $info['id']])->update(['update_time' => $time, 'status' => 2]);
                $info['id'] = 0;
            } else {
                $lottery_coupon_list = Db::name('lottery_coupon')->field('name')->where(['id' => ['IN', $info['lottery_coupon_ids']]])->select();
                $info['coupon_name'] = $lottery_coupon_list;
                switch ($info['status']) {
                    case 0:
                        $info['status_text'] = '未开启';
                        break;
                    case 1:
                        $info['status_text'] = '已开启';
                        break;
                    case 2:
                        $info['status_text'] = '已结束';
                        break;
                }
                $this->assign('info', $info);

                // 查询是否可以编辑活动
                $is_edit = true;
                $info_time_arr = explode(' - ', $info['time']);
                if ($info['status'] == 1 && time() >= strtotime($info_time_arr[0]) && time() <= strtotime($info_time_arr[1])) $is_edit = false;
                $this->assign('is_edit', $is_edit);
            }

            $lottery_coupon_list = Db::name('lottery_coupon')->where(['shop_id' => $shop_id])->order('id asc')->select();
            $this->assign('lottery_coupon_list', $lottery_coupon_list);

            $this->assign('title', '活动设置');
            return $this->fetch();
        }
    }

    /**
     * 开启活动
     * */
    public function startActivity()
    {
        $input = Request()->param();

        $id = $input['id'];

        if (empty($id)) apiReturn(2, '活动ID缺失');

        $res = Db::name('activity')->where(['id' => $id])->update(['status' => 1, 'update_time' => time()]);
        if ($res) {
            adminReturn(1, '操作成功');
        } else {
            adminReturn(2, '操作失败');
        }
    }

    /**
     * 结束活动
     * */
    public function endActivity()
    {
        $input = Request()->param();

        $id = $input['id'];

        if (empty($id)) apiReturn(2, '活动ID缺失');

        $res = Db::name('activity')->where(['id' => $id])->update(['status' => 2, 'update_time' => time()]);
        if ($res) {
            adminReturn(1, '操作成功');
        } else {
            adminReturn(2, '操作失败');
        }
    }

    /**
     * 删除活动
     * */
    public function delActivity()
    {
        $id = Request()->param('id');

        if (empty($id)) adminReturn(2, '参数丢失');

        $res = Db::name('activity')->where(['id' => $id])->delete();
        if ($res) {
            adminReturn(1, '删除活动成功', url('setActivity'));
        } else {
            adminReturn(2, '删除活动失败');
        }
    }

    /**
     * 实物券列表
     * */
    public function lotteryCouponList()
    {
        $list = Db::name('lottery_coupon')->where(['is_del' => 0])->order('create_time desc')->paginate();

        $this->assign('list', $list);

        $this->assign('title', '实物券列表');

        return $this->fetch();
    }


    /**
     * 新增/编辑 优惠券
     * */
    public function doLotteryCoupon()
    {
        if (Request()->isPost()) {
            $input = Request()->param();

            $id = $input["id"];
            $img = $input["img"];
            $name = $input["name"];
            $goods_id = $input['goods_id'];
            $count = $input["count"];
            $shop_id = session('shop_id');

            if (empty($name)) adminReturn(2, "请输入券名称");

            $where['name'] = $name;
            $where['shop_id'] = $shop_id;
            $where['is_del'] = 0;
            if ($id) $where['id'] = ['neq', $id];
            $coupon_count = Db::name('lottery_coupon')->where($where)->count();
            if ($coupon_count) adminReturn(2, '该实物券已存在');

            $data = [
                "img" => $img,
                "name" => $name,
                "goods_id" => $goods_id,
                "copy_count" => $count,
                "count" => $count
            ];

            if ($shop_id) $data['shop_id'] = $shop_id;

            if ($id > 0) {
                $res = Db::name('lottery_coupon')->where(['id' => $id])->update($data);
                if ($res) {
                    adminReturn(1, '编辑实物券成功', url('lotteryCouponList'));
                } else {
                    adminReturn(2, '编辑实物券失败或未编辑');
                }
            } else {
                $data["create_time"] = time();
                $res = Db::name('lottery_coupon')->insert($data);
                if ($res) {
                    adminReturn(1, '新增实物券成功', url('lotteryCouponList'));
                } else {
                    adminReturn(2, '新增实物券失败');
                }
            }
        } else {
            $id = Request()->param('id');

            if ($id) $info = Db::name('lottery_coupon')->where(['id' => $id])->find();
            $this->assign('info', $info);

            $goods_list = Db::name('goods')->where(['upper' => 1])->select();
            $this->assign('goods_list', $goods_list);

            $this->assign('title', ($id ? '编辑' : '新增') . '实物券');

            return $this->view->fetch();
        }
    }

    /**
     *删除优惠券
     */
    public function delLotteryCoupon()
    {
        $id = Request()->param('id');
        if (empty($id)) adminReturn(2, '参数丢失');
        $res_de_coupon = Db::name('lottery_coupon')->where(['id' => $id])->setField('is_del', 1);
        if ($res_de_coupon) {
            adminReturn(1, '删除优惠券成功', url('lotteryCouponList'));
        } else {
            adminReturn(2, '删除优惠券失败');
        }
    }

    /**
     * 公告列表
     */
    public function msgList()
    {
        $input = Request()->param();

        $title = $input['title'];
        if ($title) $where['title'] = ["like", '%' . $title . '%'];
        $list = Db::name('msg')->where($where)->order('create_time desc')->paginate();


        $this->assign('list', $list);

        $this->assign('title', '公告列表');

        return $this->fetch();
    }

    /**
     * 公告列表
     */
    public function msgListBak()
    {
        $input = Request()->param();

        $title = $input['title'];
        $where["type"] = 3;
        if ($title) $where['title'] = ["like", '%' . $title . '%'];
        $list = Db::name('msg')->where($where)->order('create_time desc')->paginate();


        $this->assign('list', $list);

        $this->assign('title', '公告列表');

        return $this->fetch();
    }

    /**
     * 新增/编辑 公告
     */
    public function doMsg()
    {
        if (Request()->isPost()) {
            $input = Request()->param();
            $id = $input['id'];
            $title = $input["title"];
            $content = $input["content"];

            if (empty($title)) adminReturn(2, "请输入标题");
            if (empty($content)) adminReturn(2, "请填写公告内容");

            if ($id) {
                $data = [
                    'title' => $title,
                    'content' => $content
                ];

                $res = Db::name('msg')->where(['id' => $id])->update($data);
            } else {
                $data = [
                    "user_id" => 0,
                    "title" => $title,
                    "content" => $content,
                    "create_time" => time()
                ];

                $res = Db::name('msg')->insert($data);
            }

            if ($res) {
                adminReturn(1, ($id ? '编辑' : '新增') . '公告成功', url('msgList'));
            } else {
                adminReturn(2, ($id ? '编辑' : '新增') . '公告失败');
            }
        } else {
            $id = Request()->param('id');

            if ($id) $info = Db::name('msg')->where(['id' => $id])->find();

            $this->assign('info', $info);
            $this->assign('title', ($id ? '公告详情' : '新增公告'));

            return $this->view->fetch();
        }
    }

    /**
     * 删除公告
     */
    public function delMsg()
    {
        $input = Request()->param();

        $id = $input["id"];

        if ($id > 0) {
            $res = Db::name('msg')->where(['id' => $id])->delete();
            if ($res) {
                adminReturn(1, '删除公告成功', url('msgList'));
            } else {
                adminReturn(2, '删除公告失败');
            }
        }
    }

    /**
     * 套餐认养协议
     * */
    public function mealArticle()
    {
        if (Request()->isPost()) {
            $input = Request()->param();

            $content = $input['content'];

            if (empty($content)) adminReturn(2, '请输入内容');

            $time = time();
            $data = [
                'content' => $content
            ];

            $count = Db::name('meal_article')->count();

            if ($count > 0) {
                //编辑
                $data['update_time'] = $time;

                $res = Db::name('meal_article')->where('1 = 1')->update($data);
                if ($res) {
                    adminReturn(1, '编辑成功', url('mealArticle'));
                } else {
                    adminReturn(2, '编辑失败');
                }
            } else {
                //新增
                $data['create_time'] = $time;

                $res = Db::name('meal_article')->insert($data);
                if ($res) {
                    adminReturn(1, '新增成功', url('mealArticle'));
                } else {
                    adminReturn(2, '新增失败');
                }
            }
        } else {
            $count = Db::name('meal_article')->count();
            $info = Db::name('meal_article')->find();

            $this->assign('title', ($count > 0 ? '编辑' : '新增') . '套餐认养协议');
            $this->assign('info', $info);

            return $this->view->fetch();
        }
    }

    /**
     * 联系我们
     * */
    public function aboutUs()
    {
        if (Request()->isPost()) {
            $input = Request()->param();

            $content = $input['content'];

            if (empty($content)) adminReturn(2, '请输入内容');


            $data = [
                'content' => $content
            ];

            $res = Db::name('about_us')->where(['id' => 1])->update($data);
            if ($res) {
                adminReturn(1, '保存成功');
            } else {
                adminReturn(2, '保存失败或未编辑');
            }
        }

        $info = Db::name('about_us')->where(['id' => 1])->find();
        $this->assign('info', $info);


        $this->assign('title', '联系我们');
        return $this->fetch();


    }

    /**
     * 意见反馈
     */
    public function feedbackList()
    {
        $input = Request()->param();

        $start_time = $input['start_time'];
        $end_time = $input['end_time'];
        $where["a.id"] = ["gt", "0"];

        if (!empty($start_time) && empty($end_time)) {
            $where["a.create_time"] = ["egt", strtotime($start_time)];
        } elseif (empty($start_time) && !empty($end_time)) {
            $where["a.create_time"] = ["elt", strtotime($end_time) + 60 * 60 * 24 - 1];
        } elseif (!empty($start_time) && !empty($end_time)) {
            $where["a.create_time"] = ['between', [strtotime($start_time), strtotime($end_time) + 60 * 60 * 24 - 1]];
        }

        $list = Db::name('feedback a')->field("a.*,b.username")->join('user b', "a.user_id = b.id", "left")
            ->where($where)->order('a.create_time desc')->paginate();
        $this->assign('list', $list);

        $this->assign('title', '意见反馈列表');

        return $this->fetch();
    }

    /**
     * 汇总数据
     * */
    public function allCensus()
    {
        $shop_id = session('shop_id');

        $start_time = strtotime(date('Y-m-d'));
        $end_time = $start_time + 24 * 3600 - 1;
        if (!empty($start_time) && empty($end_time)) {
            $today_where["create_time"] = ["egt", $start_time];
        } elseif (empty($start_time) && !empty($end_time)) {
            $today_where["create_time"] = ["elt", $end_time];
        } elseif (!empty($start_time) && !empty($end_time)) {
            $today_where["create_time"] = ['between', [$start_time, $end_time]];
        }


        $where = ['is_pay' => 1, 'status' => ['neq', '7,8']];
        if ($shop_id) $where['shop_id'] = $shop_id;

        // 今日订单数
        $today_order_count = Db::name('order')->where($today_where)->where($where)->count();
        // 总订单数
        $all_order_count = Db::name('order')->where($where)->count();
        // 今日订单总额
        $today_order_price = Db::name('order')->where($today_where)->where($where)->sum('pay_price');
        // 总订单总额
        $all_order_price = Db::name('order')->where($where)->sum('pay_price');

        $data = [
            'today_order_count' => $today_order_count,
            'all_order_count' => $all_order_count,
            'today_order_price' => $today_order_price,
            'all_order_price' => $all_order_price,
        ];

        $this->assign('title', '汇总数据');
        $this->assign('info', $data);

        return $this->view->fetch();
    }

    /**
     * 订单统计
     * */
    public function orderCensus()
    {
        $shop_id = session('shop_id');

        $where = ['is_pay' => 1, 'status' => ['neq', '7,8']];
        if ($shop_id) $where['shop_id'] = $shop_id;

        $time_list = Db::name('order')->field("from_unixtime(create_time, '%Y-%m-%d') time")->distinct(true)->where($where)->order('create_time asc')->select();
        $order_list = [];
        if ($time_list) {
            foreach ($time_list as $v) {
                $time_where["create_time"] = ['between', [strtotime($v['time']), strtotime($v['time']) + 60 * 60 * 24 - 1]];

                $user_count = Db::name('order')->where($time_where)->where($where)->count();
                $order_list[] = $user_count;
            }
        }

        $this->assign('time_list', json_encode(array_column($time_list, 'time')));
        $this->assign('order_list', json_encode($order_list));

        $this->assign('title', '订单统计');

        return $this->fetch();
    }

    /**
     * 客户统计
     * */
    public function userCensus()
    {
        $shop_id = session('shop_id');

        if ($shop_id) $where['shop_id'] = $shop_id;

        $time_list = Db::name('customer')->field("from_unixtime(create_time, '%Y-%m-%d') time")->distinct(true)->where($where)->order('create_time asc')->select();
        $user_list = [];
        if ($time_list) {
            foreach ($time_list as $v) {
                $where["create_time"] = ['between', [strtotime($v['time']), strtotime($v['time']) + 60 * 60 * 24 - 1]];

                $user_count = Db::name('customer')->where($where)->count();
                $user_list[] = $user_count;
            }
        }

        $this->assign('time_list', json_encode(array_column($time_list, 'time')));
        $this->assign('user_list', json_encode($user_list));

        $this->assign('title', '客户统计');

        return $this->fetch();
    }

    /**
     * 销售统计
     * */
    public function salesCensus()
    {
        $input = Request()->param();

        $start_time = $input['start_time'];
        $end_time = $input['end_time'];
        $shop_id = session('shop_id');
        $user_id = $input['user_id'];

        if (!empty($start_time) && empty($end_time)) {
            $where["create_time"] = ["egt", strtotime($start_time)];
            $price_where["a.create_time"] = ["egt", strtotime($start_time)];
        } elseif (empty($start_time) && !empty($end_time)) {
            $where["create_time"] = ["elt", strtotime($end_time) + 60 * 60 * 24 - 1];
            $price_where["a.create_time"] = ["elt", strtotime($end_time) + 60 * 60 * 24 - 1];
        } elseif (!empty($start_time) && !empty($end_time)) {
            $where["create_time"] = ['between', [strtotime($start_time), strtotime($end_time) + 60 * 60 * 24 - 1]];
            $price_where["a.create_time"] = ['between', [strtotime($start_time), strtotime($end_time) + 60 * 60 * 24 - 1]];
        }

        if ($shop_id) $where['shop_id'] = $shop_id;

        if ($user_id) {
            $where['user_id'] = $user_id;
            $price_where['a.user_id'] = $user_id;
        }
        $all_goods_pay_price = Db::name('order a')->join('user b', "a.user_id = b.id", "left")->where($price_where)->where(['a.is_pay' => 1])->sum('pay_price');
        $this->assign('all_goods_pay_price', sprintf('%.2f', $all_goods_pay_price));

        $time_list = Db::name('order')->field("from_unixtime(create_time, '%Y-%m-%d') time")->distinct(true)
            ->where(['is_pay' => 1, 'status' => ['neq', '7,8']])
            ->where($where)
            ->order('create_time asc')->select();

        $order_list = [];
        if ($time_list) {
            foreach ($time_list as $v) {
                $order_where["create_time"] = ['between', [strtotime($v['time']), strtotime($v['time']) + 60 * 60 * 24 - 1]];
                unset($where['create_time']);

                $order_pay_price = Db::name('order')->where(['is_pay' => 1, 'status' => ['neq', '1,7,8']])->where($where)->where($order_where)->sum('pay_price');
                $order_list[] = $order_pay_price;
            }
        }

        $this->assign('time_list', json_encode(array_column($time_list, 'time')));
        $this->assign('order_list', json_encode($order_list));

        $shop_list = Db::name('shop')->where(['is_del' => 0])->select();
        $this->assign('shop_list', $shop_list);

        $user_list = Db::name('customer c')->field('u.id,u.username')->join('cater_user u', 'c.user_id = u.id', 'left')->where(['c.shop_id' => $shop_id])->select();
        $this->assign('user_list', $user_list);

        $this->assign('title', '销售统计');

        return $this->fetch();
    }
}
